from datetime import datetime

from flask_cors import CORS
from flask import Flask, request, jsonify

from config import database
from qa import llm
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

# 加载配置信息
app.config.from_object(database.Config)

db = SQLAlchemy(app)

CORS(app)


# 创建问答记录模型类
# nullable=False表示不能为空
class Record(db.Model):
    __tablename__ = 'record'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), nullable=False)
    question = db.Column(db.String(5000), nullable=False)
    answer = db.Column(db.String(5000), nullable=False)
    operate_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)

    # 构造函数定义
    def __init__(self, username, question, answer, operate_time):
        self.username = username
        self.password = question
        self.name = answer
        self.avatar = operate_time


# 创建用户模型类
# nullable=False表示不能为空
class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), nullable=False)
    password = db.Column(db.String(50), nullable=False)
    name = db.Column(db.String(50), nullable=False)
    avatar = db.Column(db.String(255), nullable=False)
    sex = db.Column(db.Integer, nullable=False)
    phone = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(50), nullable=False)
    address = db.Column(db.String(50), nullable=False)
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    update_time = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    status = db.Column(db.SmallInteger, nullable=False)

    # 构造函数定义
    def __init__(self, username, password, name, avatar, sex, phone, email, address, create_time, update_time, status):
        self.username = username
        self.password = password
        self.name = name
        self.avatar = avatar
        self.sex = sex
        self.phone = phone
        self.email = email
        self.address = address
        self.create_time = create_time
        self.update_time = update_time
        self.status = status


# 创建角色模型类
class Role(db.Model):
    __tablename__ = 'role'
    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, nullable=False)
    role_name = db.Column(db.String(50), nullable=False)

    # 构造函数定义
    def __init__(self, role_id, role_name):
        self.role_id = role_id
        self.role_name = role_name


# 创建用户角色关联模型类
class UserRole(db.Model):
    __tablename__ = 'user_role'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, nullable=False)
    role_id = db.Column(db.Integer, nullable=False)

    # 构造函数定义
    def __init__(self, user_id, role_id):
        self.user_id = user_id
        self.role_id = role_id


# 创建菜单模型类
class Menu(db.Model):
    __tablename__ = 'menu'
    id = db.Column(db.Integer, primary_key=True)
    menu_name = db.Column(db.String(50), nullable=False)
    menu_url = db.Column(db.String(50), nullable=False)

    # 构造函数定义
    def __init__(self, menu_name, menu_url):
        self.menu_name = menu_name
        self.menu_url = menu_url


# 创建角色菜单关联模型类
class RoleMenu(db.Model):
    __tablename__ = 'role_menu'
    id = db.Column(db.Integer, primary_key=True)
    role_id = db.Column(db.Integer, nullable=False)
    menu_id = db.Column(db.Integer, nullable=False)

    # 构造函数定义
    def __init__(self, role_id, menu_id):
        self.role_id = role_id
        self.menu_id = menu_id


# 在应用程序上下文中存储对话历史
app.config['history'] = []

'''
登录服务
'''


@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    password = request.args.get('password')

    code = 200
    data = {}
    message = ''

    # 查询用户名是否存在
    user = User.query.filter_by(username=username).first()
    if user:
        # 用户存在，检查密码是否匹配
        if user.password != password:
            # 密码错误
            code = 400
            message = '密码错误'
        elif user.status == 0:
            code = 500
            message = '账号被禁用'
        else:
            # 查询用户角色信息
            user_role = UserRole.query.filter_by(user_id=user.id).first()
            role_id = user_role.role_id
            # 获取到对应角色
            role = Role.query.filter_by(id=role_id).first()
            user_role_id = role.role_id

            code = 200
            data['user_id'] = user.id
            data['username'] = user.username
            data['role_id'] = user_role_id
            data['name'] = user.name
            message = '登录成功'
    else:
        code = 300
        message = '用户不存在'

    # 返回 JSON 格式的响应
    response = {
        'code': code,
        'data': data,
        'message': message
    }
    return jsonify(response)


'''
问答服务
'''


@app.route('/ask', methods=['GET', 'POST'])
def ask():
    question = request.args.get('question')
    answer = request.args.get('answer')
    clear = request.args.get('clear')
    print(question)
    print(answer)
    print(clear)

    history = app.config['history']

    # request中获取字符串
    if int(clear) == 0:
        history.clear()

    # 将回答添加到历史对话
    if len(answer) > 0:
        history.append({'role': 'assistant', 'content': answer})

    # 将问题添加到历史对话
    history.append({'role': 'user', 'content': question})

    print(history)

    response = llm.gpt_35_api(history)

    return jsonify(response)


'''
提示词优化服务
'''


@app.route('/prompt', methods=['GET', 'POST'])
def prompt():
    question = request.args.get('question')

    history = app.config['history']

    history.append({'role': 'system',
                    'content': '你是一个提示词优化工程师，你需要对下面的问题进行优化设计，使得问题变得更加全面和清晰， ，并且只输出优化后的问题'})

    # 将问题添加到历史对话
    history.append({'role': 'user', 'content': question})

    response = llm.gpt_35_api(history)

    return jsonify(response)


'''
查询所有用户信息（管理端）
'''


@app.route("/query/user", methods=['GET', 'POST'])
def userMessage():
    # 设置分页参数
    page_num = request.args.get('page_num', 1, type=int)
    page_size = request.args.get('page_size', 10, type=int)

    users = User.query.paginate(page=page_num, per_page=page_size)

    # 将分页对象转换为 JSON 格式
    data = {
        'total': users.total,
        'pages': users.pages,
        'page': users.page,
        'per_page': users.per_page,
        'users': []
    }

    for user in users.items:
        user_data = {
            'id': user.id,
            'username': user.username,
            'password': user.password,
            'name': user.name,
            'sex': user.sex,
            'phone': user.phone,
            'status': user.status,
            'update_time': user.update_time.strftime('%Y-%m-%d %H:%M:%S'),
        }
        data['users'].append(user_data)

    # 返回JSON格式的查询结果
    return jsonify(data)


'''
查询当前用户操作纪录服务（用户端）
'''


@app.route("/query/userRecords", methods=["GET", "POST"])
def userRecords():
    username = request.args.get("username")
    records = Record.query.filter_by(username=username).all()

    # 将查询结果转换为 JSON 格式
    data = []
    for record in records:
        record_data = {
            'id': record.id,
            'question': record.question,
            'answer': record.answer,
            # 将 operate_time 转换为字符串格式
            'operate_time': record.operate_time.strftime('%Y-%m-%d %H:%M:%S')
        }
        data.append(record_data)
    # 返回JSON格式的查询结果
    return jsonify(data)


'''
查询所有用户操作纪录服务（管理端）
'''


@app.route("/query/allRecords", methods=["GET", "POST"])
def allRecord():
    records = Record.query.all()

    # 将查询结果转换为 JSON 格式
    data = []
    for record in records:
        record_data = {
            'id': record.id,
            'username': record.username,
            'question': record.question,
            'answer': record.answer,
            # 将 operate_time 转换为字符串格式
            'operate_time': record.operate_time.strftime('%Y-%m-%d %H:%M:%S')
        }
        data.append(record_data)

    # 返回JSON格式的查询结果
    return jsonify(data)


if __name__ == '__main__':
    app.run()
